﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Linq;
using SY.Uap.Entity;
using Tools.Json;

using SY.WebSite.Entity;
using SY.WebSite.BLL;

namespace SY.WebSite.Web.Handler
{
    public class LotteryHandler : InternalWebHandler, IHttpHandler
    {
        public new void ProcessRequest(HttpContext context)
        {
            base.ProcessRequest(context);

            switch (Action)
            {
                case "list":
                    List();
                    break;
                case "join":
                    Join();
                    break;
                case "open":
                    Open();
                    break;
            }

            context.Response.End();
        }

        public void Open()
        {
            int id = Tools.Web.Request.GetFormInt("id", 0);
            if (id <= 0)
                BreakResponse();

            IEnumerable<Lottery> all = BizLottery.GetAll();
            Lottery current = all.FirstOrDefault(l => l.Id == id && l.Status == 0 && l.OpenTime <= DateTime.Now && l.UserId == CurrentUser.UserId);
            if (current == null)
                BreakResponse();

            string jobNumber = Tools.Web.Request.GetFormString("jobNumber");
            User user = BizUser.GetByJobNumber(jobNumber);
            if (user == null)
                BreakResponse("中奖用户不存在");
            if (!current.Participants.Contains("," + user.UserId + ","))
                BreakResponse("参数异常，中奖用户未参与该抽奖");

            current.WinnerId = user.UserId;
            current.Winner = user.UserName + "(" + user.JobNumber + ")";
            current.Status = 1;

            int result = BizLottery.Update(current);
            if (result > 0)
            {
                Response.Write(new JsonTransfer().Add("success", "success"));
                Response.End();
            }

            current.Status = 0;
            current.Winner = "";
            current.WinnerId = 0;

            BreakResponse();
        }

        public void Join()
        {
            int id = Tools.Web.Request.GetFormInt("id", 0);
            if (id <= 0)
                BreakResponse();

            IEnumerable<Lottery> all = BizLottery.GetAll();
            Lottery current = all.First(l => l.Id == id && l.OpenTime > DateTime.Now);
            if (current == null)
                BreakResponse();
            if (current.Participants.Contains("," + CurrentUser.UserId + ","))
                BreakResponse("您已经参与该抽奖，请刷新页面");

            Integration integration = BizIntegration.GetByKey(CurrentUser.UserId);
            if (integration.Available < current.LimitAmount || integration.Available < current.CostAmount)
                BreakResponse("您的素币不足，无法参加该抽奖");

            if (BizAuctionItemBid.CheckUserHaveBidding(CurrentUser.UserId))
            {
                BreakResponse("当前存在尚未结算的拍卖纪录，暂时不能参加该抽奖");
            }

            string temp = current.Participants;
            current.Participants = (current.Participants + "," + CurrentUser.UserId + ",").Replace(",,", ",");
            int result = BizLottery.Update(current);
            if (result > 0)
            {
                IntegrationTransaction transaction = new IntegrationTransaction
                    {
                        ToUserId = CurrentUser.UserId,
                        ToUserName = CurrentUser.UserName,
                        Comment = "参与抽奖《" + current.Title + "》",
                        Amount = current.CostAmount,
                        Type = 2,
                        TargetId = current.Id
                    };
                if (BizIntegrationTransaction.Add(transaction) > 0)
                {
                    integration.Available -= current.CostAmount;
                    BizIntegration.Update(integration);
                }

                Response.Write(new JsonTransfer().Add("success", "success"));
                Response.End();
            }
            current.Participants = temp;
            BreakResponse();
        }

        public void List()
        {
            JsonTransfer jt = new JsonTransfer();
            IEnumerable<Lottery> all = BizLottery.GetAll();
            int type = RequestIntParam("type");
            int pageIndex = RequestIntParam("pageIndex");
            int pageSize = RequestIntParam("pageSize", 15);
            
            switch (type) {
                case 1:
                    all = all.Where(l => l.Status == 0);
                    break;
                case 2:
                    all = all.Where(l => l.Status == 1);
                    break;
                case 3:
                    all = all.Where(l=>!string.IsNullOrEmpty(l.Participants) && l.Participants.Contains(","+ CurrentUser.UserId+","));
                    break;
            }

            jt.Add("count", all.Count());
            jt.Add("list", all.Skip(pageIndex * pageSize).Take(pageSize));
            Response.Write(jt);
        }
    }
}